<template>
  <div class="task-container">
    <!-- Header -->
    <div class="task-header">
      <div class="header-left">
        <h1>TaskMaster</h1>
        <span class="user-info" v-if="authStore.user">
          欢迎，{{ authStore.user.username }}
        </span>
      </div>
      <div class="header-right">
        <el-button @click="handleLogout" type="text">登出</el-button>
      </div>
    </div>

    <!-- Toolbar -->
    <div class="task-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          新建任务
        </el-button>
        <el-button-group>
          <el-button
            :type="tasksStore.currentView === 'list' ? 'primary' : ''"
            @click="switchView('list')"
          >
            <el-icon><List /></el-icon>
            列表视图
          </el-button>
          <el-button
            :type="tasksStore.currentView === 'kanban' ? 'primary' : ''"
            @click="switchView('kanban')"
          >
            <el-icon><Grid /></el-icon>
            看板视图
          </el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索任务..."
          style="width: 200px"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- Task Content -->
    <div class="task-content">
      <!-- List View -->
      <div v-if="tasksStore.currentView === 'list'" class="list-view">
        <el-table
          :data="filteredTasks"
          style="width: 100%"
          :loading="tasksStore.loading"
          stripe
        >
          <el-table-column prop="title" label="任务标题" min-width="200">
            <template #default="scope">
              <div class="task-title">
                <span>{{ scope.row.title }}</span>
                <el-tag
                  :type="tasksStore.getPriorityColor(scope.row.priority)"
                  size="small"
                  class="priority-tag"
                >
                  {{ tasksStore.getPriorityText(scope.row.priority) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="150">
            <template #default="scope">
              <span class="description">{{ scope.row.description || '无描述' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="due_date" label="截止时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.due_date) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="120">
            <template #default="scope">
              <el-tag :type="tasksStore.getStatusColor(scope.row.status)">
                {{ tasksStore.getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button-group>
                <el-button
                  size="small"
                  @click="editTask(scope.row)"
                  type="primary"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  @click="deleteTask(scope.row.id)"
                  type="danger"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- Kanban View -->
      <div v-else class="kanban-view">
        <div class="kanban-columns">
          <div class="kanban-column">
            <div class="column-header">
              <h3>待办</h3>
              <span class="task-count">{{ tasksStore.getPendingTasks.length }}</span>
            </div>
            <div class="column-content">
              <div
                v-for="task in tasksStore.getPendingTasks"
                :key="task.id"
                class="task-card"
                @click="editTask(task)"
              >
                <h4>{{ task.title }}</h4>
                <p>{{ task.description || '无描述' }}</p>
                <div class="task-meta">
                  <el-tag :type="tasksStore.getPriorityColor(task.priority)" size="small">
                    {{ tasksStore.getPriorityText(task.priority) }}
                  </el-tag>
                  <span class="due-date">{{ formatDate(task.due_date) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="kanban-column">
            <div class="column-header">
              <h3>进行中</h3>
              <span class="task-count">{{ tasksStore.getInProgressTasks.length }}</span>
            </div>
            <div class="column-content">
              <div
                v-for="task in tasksStore.getInProgressTasks"
                :key="task.id"
                class="task-card"
                @click="editTask(task)"
              >
                <h4>{{ task.title }}</h4>
                <p>{{ task.description || '无描述' }}</p>
                <div class="task-meta">
                  <el-tag :type="tasksStore.getPriorityColor(task.priority)" size="small">
                    {{ tasksStore.getPriorityText(task.priority) }}
                  </el-tag>
                  <span class="due-date">{{ formatDate(task.due_date) }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="kanban-column">
            <div class="column-header">
              <h3>已完成</h3>
              <span class="task-count">{{ tasksStore.getCompletedTasks.length }}</span>
            </div>
            <div class="column-content">
              <div
                v-for="task in tasksStore.getCompletedTasks"
                :key="task.id"
                class="task-card completed"
                @click="editTask(task)"
              >
                <h4>{{ task.title }}</h4>
                <p>{{ task.description || '无描述' }}</p>
                <div class="task-meta">
                  <el-tag :type="tasksStore.getPriorityColor(task.priority)" size="small">
                    {{ tasksStore.getPriorityText(task.priority) }}
                  </el-tag>
                  <span class="due-date">{{ formatDate(task.due_date) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Create/Edit Task Dialog -->
    <el-dialog
      v-model="showCreateDialog"
      :title="isEditing ? '编辑任务' : '新建任务'"
      width="600px"
    >
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            placeholder="请输入任务描述（可选）"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="请选择优先级">
            <el-option label="高" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="低" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="截止时间" prop="due_date">
          <el-date-picker
            v-model="taskForm.due_date"
            type="datetime"
            placeholder="选择截止时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>

        <el-form-item v-if="isEditing" label="状态" prop="status">
          <el-select v-model="taskForm.status" placeholder="请选择状态">
            <el-option label="待办" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleTaskSubmit" :loading="submitting">
            {{ isEditing ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/**
 * TaskMaster v1 - Task List View
 * AceFlow v3.0 - Implementation Phase
 */

import { ref, reactive, computed, onMounted } from 'vue'
import { useAuthStore } from '../stores/auth.js'
import { useTasksStore } from '../stores/tasks.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  List,
  Grid,
  Search
} from '@element-plus/icons-vue'

export default {
  name: 'TaskList',
  components: {
    Plus,
    List,
    Grid,
    Search
  },
  setup() {
    const authStore = useAuthStore()
    const tasksStore = useTasksStore()

    const showCreateDialog = ref(false)
    const isEditing = ref(false)
    const submitting = ref(false)
    const searchQuery = ref('')
    const taskFormRef = ref()

    const taskForm = reactive({
      id: null,
      title: '',
      description: '',
      priority: 2,
      due_date: null,
      status: 'pending'
    })

    const taskRules = {
      title: [
        { required: true, message: '请输入任务标题', trigger: 'blur' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      due_date: [
        { required: true, message: '请选择截止时间', trigger: 'change' }
      ]
    }

    const filteredTasks = computed(() => {
      if (!searchQuery.value) {
        return tasksStore.tasks
      }
      return tasksStore.tasks.filter(task =>
        task.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        (task.description && task.description.toLowerCase().includes(searchQuery.value.toLowerCase()))
      )
    })

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    const switchView = (view) => {
      tasksStore.setCurrentView(view)
    }

    const resetTaskForm = () => {
      taskForm.id = null
      taskForm.title = ''
      taskForm.description = ''
      taskForm.priority = 2
      taskForm.due_date = null
      taskForm.status = 'pending'
      isEditing.value = false
    }

    const editTask = (task) => {
      taskForm.id = task.id
      taskForm.title = task.title
      taskForm.description = task.description
      taskForm.priority = task.priority
      taskForm.due_date = task.due_date
      taskForm.status = task.status
      isEditing.value = true
      showCreateDialog.value = true
    }

    const handleTaskSubmit = async () => {
      try {
        await taskFormRef.value.validate()

        submitting.value = true

        const taskData = {
          title: taskForm.title,
          description: taskForm.description,
          priority: taskForm.priority,
          due_date: taskForm.due_date
        }

        let result
        if (isEditing.value) {
          // Update task
          const updateData = {
            ...taskData,
            status: taskForm.status
          }
          result = await tasksStore.updateTask(taskForm.id, updateData)
        } else {
          // Create task
          result = await tasksStore.createTask(taskData)
        }

        if (result.success) {
          ElMessage.success(result.message)
          showCreateDialog.value = false
          resetTaskForm()
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        console.error('Task form validation failed:', error)
      } finally {
        submitting.value = false
      }
    }

    const deleteTask = async (taskId) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除这个任务吗？此操作不可撤销。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const result = await tasksStore.deleteTask(taskId)
        if (result.success) {
          ElMessage.success(result.message)
        } else {
          ElMessage.error(result.message)
        }
      } catch (error) {
        // User cancelled
      }
    }

    const handleLogout = () => {
      authStore.logout()
    }

    // Initialize
    onMounted(async () => {
      // Wait for authentication to be initialized
      if (authStore.token && !authStore.user) {
        const authResult = await authStore.initializeAuth()
        if (!authResult) {
          // Token is invalid, auth store will handle logout and redirect
          return
        }
      }

      // Only fetch tasks if user is authenticated
      if (authStore.isAuthenticated && authStore.user) {
        const result = await tasksStore.fetchTasks()
        // If token expired, redirect to login
        if (result.redirectToLogin) {
          return
        }
      }
    })

    return {
      authStore,
      tasksStore,
      showCreateDialog,
      isEditing,
      submitting,
      searchQuery,
      taskFormRef,
      taskForm,
      taskRules,
      filteredTasks,
      formatDate,
      switchView,
      editTask,
      handleTaskSubmit,
      deleteTask,
      handleLogout
    }
  }
}
</script>

<style scoped>
.task-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.task-header {
  background: white;
  padding: 20px 30px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-left h1 {
  margin: 0;
  color: #409eff;
  font-size: 24px;
  font-weight: 600;
}

.user-info {
  color: #666;
  font-size: 14px;
}

.task-toolbar {
  background: white;
  padding: 20px 30px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-left {
  display: flex;
  gap: 15px;
  align-items: center;
}

.task-content {
  padding: 30px;
}

.list-view {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.task-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.priority-tag {
  font-size: 12px;
}

.description {
  color: #666;
  font-size: 14px;
}

.kanban-view {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.kanban-columns {
  display: flex;
  gap: 20px;
  min-height: 600px;
}

.kanban-column {
  flex: 1;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.column-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.task-count {
  background: #409eff;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.task-card {
  background: white;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.2s;
}

.task-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.task-card.completed {
  opacity: 0.7;
}

.task-card h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.task-card p {
  margin: 0 0 10px 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.task-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.due-date {
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
